<script setup>
import { ref, onMounted, watch, reactive } from 'vue';
import easyapi from '../api';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { ElForm } from 'element-plus';

import jwt_decode from 'jwt-decode';
// 解析token中的用户名
const getnameFromToken = (token) => {
  const decoded = jwt_decode(token);
  console.log(decoded); // 打印解码后的对象
  return decoded.username;
};
/***************************** */

/****************************************** */
const formRef = ref([]);
const formRefTo=ref([]);

const tableData = ref([]);
const tableData1=ref([]);
const router = useRouter();

const addWinVisible = ref(false); // 控制弹窗的显示/隐藏

const addWinVisibleTo = ref(false);

const openAddWin = () => {
  addObject.value = {};
  addWinVisible.value = true;
};
const closeAddWin = () => {
  addWinVisible.value = false;
};
const openAddWinTo = () => {
  addObjectTo.value = {};
  addWinVisibleTo.value = true;
};
const closeAddWinTo = () => {
  addWinVisibleTo.value = false;
};
const addSave =function() {
    // 这里可以添加表单验证逻辑
  formRef.value?.validate(async valid => {
    if (valid) {
      // 表单验证通过后执行提交逻辑
      addObject.value.status="已入住";
  // router.push('/room-selection'); 
  // 提交后跳转到房间选择页面
  // easyapi.postForm('/api/staff',addObject.value);
  const result = await easyapi.postForm('/api/checkinsjson', addObject.value);
  // 表格数据变更
  tableData.value.unshift(result.data);
  console.log(result);
  ElMessage({
    type: 'success',
    message: '登记成功',
  }),closeAddWin();
    } else {
      console.log('表单验证未通过');
      return false;
    }
  });
};
// 方法用于关闭弹窗并导航到下一个页面
const addSaveTo = async function() {
  formRefTo.value?.validate(async valid => {
    if (valid) {
      // 表单验证通过后执行提交逻辑
      addObjectTo.value.status="已预定";
  // router.push('/room-selection'); 
  // 提交后跳转到房间选择页面
  // easyapi.postForm('/api/staff',addObject.value);
  const result = await easyapi.postForm('/api/reservationsjson', addObjectTo.value);
    // 表格数据变更
  tableData1.value.unshift(result.data);
  console.log(result);
  ElMessage({
    type: 'success',
    message: '预定成功',
  }), closeAddWinTo();
    } else {
      console.log('表单验证未通过');
      return false;
    }
  });

};
// 绑定
const addObjectTo = ref({
  name: '',
  phone_number: '',
  id_number: '',
  number: '',
  rate: '',
  check_in_date: '',
  check_out_date: '',
  re_status:''
});
const rates = ref([220]);
const re_statuses=ref(['预定中']);

function ToXin() {
  router.push('/reservations'); // 跳转到入住登记页面
}
/*************************************************************** */
// 退出登录
const clearToken = () => {
  sessionStorage.removeItem('easytoken');
};

const logout = () => {
  ElMessageBox.confirm(
    '确定退出登录吗？',
    '提示框',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    clearToken();
    router.push('/login');
  });
};
/*************************************** */
const exit = () => {
  ElMessageBox.confirm(
    '密码修改成功，请重新登录',
    '提示框',
    {
      confirmButtonText: '确认',
      type: 'warning',
      showCancelButton: false, // 移除取消按钮
      closeOnClickModal: false, // 点击遮罩层不关闭弹框
      showClose: false // 移除关闭按钮
    }
  ).then(() => {
    clearToken();
    router.push('/login');
  });
};

/******************************************************* */

//存储空闲房间
const freeRooms=ref([]);

// 获取空闲房间
const fetchFreeRooms = async () => {
  try {
    const response = await axios.get('/api/free-rooms');
    console.log('Received data:', response.data);
    freeRooms.value = response.data.data;
  } catch (error) {
    console.error('Error fetching free rooms:', error);
    ElMessage.error('无法加载空闲房间信息，请稍后再试。');
  }
};
// 在组件挂载时获取空闲房间
onMounted(() => {
  fetchFreeRooms();
});

// 当对话框打开时重新获取空闲房间
watch(addWinVisibleTo, (newValue) => {
  if (newValue) {
    fetchFreeRooms();
  }
});


/******************************* */
//控制修改密码窗口是否显示
const editpassWinVisible=ref(false);
//绑定用户密码
const editpass=ref({});

const username=ref(sessionStorage.getItem('username'));
// 打开修改密码弹窗
const openPassWin = () => {
  const username =getnameFromToken(sessionStorage.getItem('easytoken'));
  editpass.value.username=username;
  // username.value = username; // 更新响应式数据
  editpassWinVisible.value = true;
};
// 关闭修改密码弹窗
const closePassWin = () => {
  editpassWinVisible.value = false;
};
const test=(rule, value, callback) => {
    if(editpass.value.password1 ===editpass.value.password2)
{
    callback()  
}else{
    callback(new Error('两次密码不一样'))
}
};
const formRefpass=ref([]);
const editpasssave = async function(){
    formRefpass.value.validate(async (valid) => {
        if (valid) {
                let result=await easyapi.getSearch('/api/testpassword', editpass.value);
                if (result.data==true) {
                    let editpassword=await easyapi.putForm('/api/editpassword', editpass.value);
                    if (editpassword.code==200) {
                    ElMessage.success('修改成功');
                    exit();
                } 
                 else {
                    ElMessage.error('修改失败');
                }
                closePassWin();
            }else{
              ElMessage.error('填入原密码有误，请重新输入！');
            }
            } else {
                ElMessage.error('填入信息有误，请重新输入！');
            }
        }
    )
}
const passwordrules=ref({
    userpass:[{required:true,message:'请输入原密码',trigger:'blur'}],
    password1:[{required:true,message:'请输入新密码',trigger:'blur'}],
    password2:[{validator:test,trigger:'blur'}]
})



/*************************** */
//禁用日期
// 定义 disabledDate 函数
const disabledDate = (time) => {
  // 返回 true 表示该日期被禁用
  // 这里可以根据你的业务逻辑来编写
  return time.getTime() < Date.now() - 8.64e7; // 禁用过去日期
};

/********************************************** */
const addObject = ref({
  name: '',
  number: '',
  phone_number: '',
  id_number: '',
  check_in_date: '',
  check_out_date: ''
});
//表单验证
const addrules = reactive({
  name: [
    { required: true, message: '请输入客人姓名', trigger: 'blur' },
    {
      pattern: /^[\u4e00-\u9fa5]{2,4}$/, // 匹配两到四个汉字
      message: '客人姓名必须为两到四个汉字',
      trigger: 'blur'
    }
  ],
  phone_number: [
    { required: true, message: '请输入电话号码', trigger: 'blur' },
    {
      pattern: /^(1[3-9]\d{9})$/, // 匹配以13至19开头的11位数字
      message: '输入正确的手机号',
      //'电话号码必须为11位数字，并且以13至19开头',
      trigger: 'blur'
    }
  ],
  id_number: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, // 匹配身份证号
      //15位纯数字的身份证号码。
      //18位纯数字的身份证号码。
      //18位身份证号码，其中最后一位是数字或X（大小写均可）。
      message: '请输入正确的身份证号',
      trigger: 'blur'
    }
  ],
  number: [{ required: true, message: '请选择入住房间', trigger: 'change' }],
  check_in_date: [
    { required: true, message: '请选择开始日期', trigger: 'change' }
  ],
  check_out_date: [
    { required: true, message: '请选择结束日期', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请选择结束日期'));
        }
        if (!addObject.value.check_in_date) {
          return callback(new Error('请选择开始日期'));
        }
        if (new Date(value) <= new Date(addObject.value.check_in_date)) {
          return callback(new Error('结束日期必须大于开始日期'));
        }
        callback();
      },
      trigger: 'change'
    }
  ]
});

/************************************ ***************/

const addTorules=reactive({
  name: [
    { required: true, message: '请输入客人姓名', trigger: 'blur' },
    {
      pattern: /^[\u4e00-\u9fa5]{2,4}$/, // 匹配两到四个汉字
      message: '客人姓名必须为两到四个汉字',
      trigger: 'blur'
    }
  ],
  phone_number: [
    { required: true, message: '请输入电话号码', trigger: 'blur' },
    {
      pattern: /^(1[3-9]\d{9})$/, // 匹配以13至19开头的11位数字
      message: '输入正确的手机号',
      //'电话号码必须为11位数字，并且以13至19开头',
      trigger: 'blur'
    }
  ],
  id_number: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, // 匹配身份证号
      //15位纯数字的身份证号码。
      //18位纯数字的身份证号码。
      //18位身份证号码，其中最后一位是数字或X（大小写均可）。
      message: '请输入正确的身份证号',
      trigger: 'blur'
    }
  ],
  number: [{ required: true, message: '请选择入住房间', trigger: 'change' }],
  rate: [{ required: true, message: '请选择价格', trigger: 'change' }],
  re_status: [{ required: true, message: '请填入预定状态', trigger: 'change' }],
  check_in_date: [
    { required: true, message: '请选择开始日期', trigger: 'change' }
  ],
  check_out_date: [
    { required: true, message: '请选择结束日期', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请选择结束日期'));
        }
        if (!addObjectTo.value.check_in_date) {
          return callback(new Error('请选择开始日期'));
        }
        if (new Date(value) <= new Date(addObjectTo.value.check_in_date)) {
          return callback(new Error('结束日期必须大于开始日期'));
        }
        callback();
      },
      trigger: 'change'
    }
  ]
});


/**************************** */
import image1 from '../image/1.jpg';
import image2 from '../image/2.jpg';
import image3 from '../image/3.jpg';
import image4 from '../image/5.jpg';
import image5 from '../image/12.jpg';
import image6 from '../image/6.jpg';
import image7 from '../image/7.jpg';
import image8 from '../image/8.jpg';
import image9 from '../image/19.jpg';
import image10 from '../image/12.jpg';

const carouselItems = ref([
  { src: image1 },
  { src: image2 },
  { src: image3 },
  { src: image4 },
  { src: image5 },
  { src: image6 },
  { src: image7 },
  { src: image8 },
  { src: image9 },
  { src: image10 }
]);
</script>

<template>
  
  <div class="login-container">

      <!-- 新增走马灯组件 -->
      <el-carousel :interval="2000" type="card" height="200px">
      <el-carousel-item v-for="(item, index) in carouselItems" :key="index">
        <img :src="item.src" alt="" style="width: 100%; height: 100%;">
      </el-carousel-item>
    </el-carousel>

    <div class="container">
      <el-text class="welcome-text" size="large">{{username}}欢迎使用酒店管理系统！</el-text>
      
      <div class="button-container">
        <el-button class="large-button" type="primary" plain @click="openAddWin">入住登记</el-button>
        <el-button class="large-button" type="primary" plain @click="openAddWinTo">预约新增</el-button>
        <el-button class="large-button" type="primary" plain @click="ToXin">信息管理</el-button>
      </div>

      <!--start 入住登记信息弹出框 -->
      <el-dialog v-model="addWinVisible" title="信息登记" width="500">
        <el-form :model="addObject" :rules="addrules" ref="formRef">
          <!-- <el-form-item label="预约ID" label-width="80">
            <el-input v-model="addObject.reservations_id" autocomplete="off" />
          </el-form-item> -->
          <el-form-item label="客人姓名" label-width="80" prop="name">
            <el-input v-model="addObject.name" autocomplete="off" />
          </el-form-item>
          <el-form-item label="入住房间" label-width="80" prop="number">
            <el-select v-model="addObject.number" placeholder="请选择房间号" clearable>
             <el-option v-for="room in freeRooms" :key="room.id" :label="room.number" :value="room.number" />
            </el-select>
          </el-form-item>
          <el-form-item label="电话号码" label-width="80" prop="phone_number">
            <el-input v-model="addObject.phone_number" autocomplete="off" />
          </el-form-item>
          <el-form-item label="身份证号" label-width="80" prop="id_number">
            <el-input v-model="addObject.id_number" autocomplete="off" />
          </el-form-item>
          <el-form-item label="开始日期" label-width="80" prop="check_in_date">
        <el-date-picker
          v-model="addObject.check_in_date"
          type="date"
          placeholder="入住日期"
          clearable
          :size="size"
          :shortcuts="shortcuts"
          value-format="YYYY-MM-DD"
          :disabled-date="disabledDate"
        />
      </el-form-item>
      <el-form-item label="结束日期" label-width="80" prop="check_out_date">
        <el-date-picker
          v-model="addObject.check_out_date"
          type="date"
          placeholder="退房日期"
          clearable
          value-format="YYYY-MM-DD" 
          :size="size"
          :shortcuts="shortcuts"
          :disabled-date="disabledDate"
        />
      </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="addWinVisible = false">取消</el-button>
            <el-button type="primary" @click="addSave">
              提交
            </el-button>
          </div>
        </template>
      </el-dialog>
      <!--end 入住信息弹出框 -->

      <!--start 预约新增信息弹出框 -->
      <el-dialog v-model="addWinVisibleTo" title="预约信息记录" width="500">
        <el-form :model="addObjectTo":rules="addTorules" ref="formRefTo">
          <el-form-item label="客人姓名" label-width="80" prop="name">
            <el-input v-model="addObjectTo.name" autocomplete="off" placeholder="客人姓名" clearable />
          </el-form-item>
          <el-form-item label="电话号码" label-width="80" prop="phone_number">
            <el-input v-model="addObjectTo.phone_number" autocomplete="off" placeholder="电话号码" clearable />
          </el-form-item>
          <el-form-item label="身份证号" label-width="80" prop="id_number">
            <el-input v-model="addObjectTo.id_number" autocomplete="off" placeholder="身份证号" clearable />
          </el-form-item>
          <el-form-item label="房间号" label-width="80" prop="number">
            <el-select v-model="addObjectTo.number" placeholder="请选择房间号" clearable>
             <el-option v-for="room in freeRooms" :key="room.id" :label="room.number" :value="room.number" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="房间单价" label-width="80" prop="rate">
            <el-select v-model="addObjectTo.rate" placeholder="请选择价格" clearable>
              <el-option v-for="rate in rates" :key="rate" :label="rate" :value="rate" />
            </el-select>
          </el-form-item> -->
          <el-form-item label="开始日期" label-width="80" prop="check_in_date">
            <el-date-picker
              v-model="addObjectTo.check_in_date"
              type="date"
              placeholder="入住日期"
              clearable
              :size="size"
              :shortcuts="shortcuts"
              value-format="YYYY-MM-DD"
              :disabled-date="disabledDate"
            />
          </el-form-item>
          <el-form-item label="退房日期" label-width="80" prop="check_out_date">
            <el-date-picker
              v-model="addObjectTo.check_out_date"
              type="date"
              placeholder="退房日期"
              clearable
              value-format="YYYY-MM-DD"
              :size="size"
              :shortcuts="shortcuts"
              :disabled-date="disabledDate"
            />
          </el-form-item>
          <el-form-item label="预定状态" label-width="80" prop="re_status">
            <el-select v-model="addObjectTo.re_status" placeholder="请填入预定状态" clearable>
              <el-option v-for="re_status in re_statuses" :key="re_status" :label="re_status" :value="re_status" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="addWinVisibleTo = false">取消</el-button>
            <el-button type="primary" @click="addSaveTo">
              提交
            </el-button>
          </div>
        </template>
      </el-dialog>
      <!--end 入住信息弹出框 -->

        <!-- 修改密码弹窗-->
        <el-dialog v-model="editpassWinVisible" title="修改密码" width="500">
    <el-form label-width="120px" size="small" :model="editpass" :rules="passwordrules" ref="formRefpass">
 <el-form-item label="用户名">
        <el-input v-model="editpass.username" autocomplate="off" readonly></el-input>
      </el-form-item>
      <el-form-item label="原密码" prop="userpass">
        <el-input v-model="editpass.userpass" autocomplate="off" show-password></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="password1">
        <el-input v-model="editpass.password1" autocomplate="off" show-password></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="password2">
        <el-input v-model="editpass.password2" autocomplate="off" show-password></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="editpasssave">确认</el-button>
      </el-form-item>
    </el-form>
</el-dialog>


      <!-- 退出登录和个人中心按钮 -->
      <div class="top-right-buttons">
        <el-button type="primary" plain @click="logout">退出登录</el-button>
        <el-button type="primary" plain @click="openPassWin">修改密码</el-button>
      </div>
    </div>
  </div>
</template>


<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-image: url('../image/1.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  position: relative; /* 添加绝对定位 */
  z-index: 1; /* 设置z-index以确保走马灯组件在其上方 */
}

.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #ecf0f5; /* 背景颜色可以根据需要调整 */
}

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start; /* 更改为flex-start以对齐顶部 */
  height: 70vh; /* 使容器占据整个视口高度 */
  text-align: center;
}

.welcome-text {
  font-family: 'SimSun', serif; /* 使用宋体，如果没有则使用serif */
  font-weight: bold; /* 加粗字体 */
  font-size: 70px;
  margin-bottom: 0px;
  color: #eff5fa; /* 设置为白色 */
  margin-top: 70px;
}

.button-container {
  display: flex;
  justify-content: center;
  gap: 40px; /* 为按钮间增加间距 */
  margin-top: 60px; /* 向下移动40像素 */
}

.large-button {
  font-size: 30px; /* 增加按钮字体大小 */
  padding: 60px 60px; /* 增加按钮内边距 */
}

.edit-profile-form {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.top-right-buttons {
  position: absolute;
  top: 20px;
  right: 20px;
}


/* 走马灯样式 */
.el-carousel {
  position: absolute; /* 添加绝对定位 */
  top: 75%; /* 调整top值以控制距离顶部的距离 */
  left: 50%; /* 居中对齐 */
  transform: translateX(-50%); /* 水平居中 */
  z-index: 2; /* 确保走马灯在背景图片之上 */
  width: 100%; /* 调整宽度以适应屏幕 */
  height: 200px; /* 固定高度 */
}

/* 图片样式 */
.el-carousel__item img {
  width: 100%;
  height: 300%;
  object-fit: cover;
}

</style>